package com.masterclient.app.modules.purchase;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.bean.order.ConfirmOrderData;
import com.eoner.baselibrary.bean.purchase.PurchaseCartData;
import com.eoner.baselibrary.bean.purchase.PurchaseCartItemBean;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.base.ProgressLoginDialog;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.modules.purchase.adapter.PurchaseShopCartAdapter;
import com.masterclient.app.modules.purchase.contract.PurchaseShopCartContract;
import com.masterclient.app.modules.purchase.contract.PurchaseShopCartPresenter;
import com.masterclient.app.modules.purchase.widget.PurchaseShopCartEditDialog;
import com.masterclient.app.modules.purchase.widget.SelectGoodsDialog;
import com.masterclient.app.widget.TitlebarView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * Author：hxm
 */
@Route(path = AroutePath.PURCHASE_SHOP_CART_ACTIVITY)
public class NewPurchaseShopCartActivity extends BaseActivity<PurchaseShopCartPresenter> implements PurchaseShopCartContract.View {

    @BindView(R.id.purchase_cart_bar)
    TitlebarView purchaseCartBar;
    @BindView(R.id.purchase_cart_notice_text)
    TextView purchaseCartNoticeText;
    @BindView(R.id.purchase_cart_notice_icon)
    ImageView purchaseCartNoticeIcon;
    @BindView(R.id.purchase_cart_notice_layout)
    LinearLayout purchaseCartNoticeLayout;
    @BindView(R.id.purchase_cart_confirm)
    TextView purchaseCartConfirm;
    @BindView(R.id.purchase_cart_selected_icon)
    ImageView purchaseCartSelectedIcon;
    @BindView(R.id.purchase_cart_selected_layout)
    FrameLayout purchaseCartSelectedLayout;
    @BindView(R.id.purchase_cart_price)
    TextView purchaseCartPrice;
    @BindView(R.id.purchase_cart_num)
    TextView purchaseCartNum;
    @BindView(R.id.purchase_cart_bottom_layout)
    ConstraintLayout purchaseCartBottomLayout;
    @BindView(R.id.purchase_cart_recycler)
    RecyclerView purchaseCartRecycler;
    @BindView(R.id.tv_purchase_cart_delete)
    TextView tvPurchaseCartDelete;
    @BindView(R.id.view_all_info)
    View viewAllInfo;

    private View emptyView;
    private ProgressLoginDialog progressDialog;
    private PurchaseShopCartAdapter cartAdapter;
    private PurchaseCartData cartData;
    private String cart_ids;
    private List<String> selectedList;
    private boolean isAllSelected = false;
    private boolean isEdit = true;
    private int clickPos;
    private String cartId;
    private RxBus rxBus;
    private SelectGoodsDialog goodsDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_purchase_shop_cart);
        ButterKnife.bind(this);

        selectedList = new ArrayList<>();
        cart_ids = "";
        emptyView = View.inflate(this, R.layout.null_collect, null);
        ((TextView) emptyView.findViewById(R.id.tv_tip)).setText("您的采购清单是空的哦~");
        cartAdapter = new PurchaseShopCartAdapter();
        cartAdapter.setEmptyView(emptyView);
        emptyView.setVisibility(View.GONE);
        purchaseCartRecycler.setLayoutManager(new LinearLayoutManager(this));
        purchaseCartRecycler.setItemAnimator(null);
        cartAdapter.bindToRecyclerView(purchaseCartRecycler);

        Utils.setDin(purchaseCartPrice, this);
        initListener();

        rxBus = RxBus.$();
        rxBus.OnEvent(rxBus.register(Config.SUBMIT_ORDER), o -> {
            if (selectedList != null && selectedList.size() > 0) {
                selectedList.clear();
            }
        });

        rxBus.OnEvent(rxBus.register(Config.PURCHASE_SUBMIT_ORDER), new Consumer<Object>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull Object o) throws Exception {
                if (goodsDialog != null) goodsDialog.dismiss();
            }
        });
    }

    private void initListener() {
        purchaseCartBar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {
                if (purchaseCartBar.getRightText().equals("编辑")) {
                    isEdit = false;
                    purchaseCartBar.setRightText("完成");
                    purchaseCartConfirm.setVisibility(View.GONE);
                    tvPurchaseCartDelete.setVisibility(View.VISIBLE);
                    viewAllInfo.setVisibility(View.GONE);
                } else {
                    isEdit = true;
                    purchaseCartBar.setRightText("编辑");
                    purchaseCartConfirm.setVisibility(View.VISIBLE);
                    tvPurchaseCartDelete.setVisibility(View.GONE);
                    viewAllInfo.setVisibility(View.VISIBLE);
                }
                doEditStatus();
            }
        });

        cartAdapter.setOnItemClickListener((adapter, view, position) ->
                ARouter.getInstance().build(AroutePath.PURCHASE_PRODUCT_DETAIL_ACTIVITY)
                        .withString("product_id", cartAdapter.getData().get(position).getProduct_main_id())
                        .navigation());

        cartAdapter.setOnPurchaseShopCartListener(new PurchaseShopCartAdapter.OnPurchaseShopCartListener() {
            @Override
            public void onMainGoodsCheck(String productId, boolean isSelected) {
                doMainGoodsCheck(productId, isSelected);
            }

            @Override
            public void onSkuGoodsCheck(String productId, String carId, boolean isSelected) {
                doSkuGoodsCheck(productId, carId, isSelected);
            }

            @Override
            public void onSkuReduce(PurchaseCartItemBean itemBean) {
                cartId = itemBean.getCart_id();
                if (1 >= Long.parseLong(itemBean.getBuy_qty())) {
                    ToastUtil.showToast("请至少添加一件哦");
                    return;
                }
                showProgress();
                mPresenter.updateData(itemBean.getCart_id(), Long.parseLong(itemBean.getBuy_qty()) > Long.parseLong(
                        itemBean.getStock()) ? itemBean.getStock() : String.valueOf(Long.parseLong(itemBean.getBuy_qty()) - 1));

            }

            @Override
            public void onSkuAdd(PurchaseCartItemBean itemBean) {
                cartId = itemBean.getCart_id();
                if (Long.parseLong(itemBean.getStock()) <= Long.parseLong(itemBean.getBuy_qty())) {
                    ToastUtil.showToast("没有更多库存了");
                    return;
                }
                showProgress();
                mPresenter.updateData(itemBean.getCart_id(), String.valueOf(Long.parseLong(itemBean.getBuy_qty()) + 1));

            }

            @Override
            public void onEditClick(PurchaseCartItemBean itemBean) {
                showInputDialog(itemBean, itemBean.getBuy_qty());
            }
        });
    }

    /**
     * 输入弹窗
     */
    public void showInputDialog(PurchaseCartItemBean itemBean, String num) {
        PurchaseShopCartEditDialog liveInputTextMsgDialog = null;
        if (liveInputTextMsgDialog == null){
            liveInputTextMsgDialog = new PurchaseShopCartEditDialog(this, R.style.InputDialog, num);
            PurchaseShopCartEditDialog finalLiveInputTextMsgDialog = liveInputTextMsgDialog;
            liveInputTextMsgDialog.setmOnTextSendListener(msg -> {
                finalLiveInputTextMsgDialog.dismiss();
                showProgress();
                mPresenter.updateData(itemBean.getCart_id(), msg);
            });
            WindowManager.LayoutParams lp = liveInputTextMsgDialog.getWindow().getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            liveInputTextMsgDialog.getWindow().setAttributes(lp);
            liveInputTextMsgDialog.setCancelable(true);
            liveInputTextMsgDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            if (!liveInputTextMsgDialog.isShowing()){
                liveInputTextMsgDialog.show();
            }
        }
        purchaseCartRecycler.postDelayed(() -> {
            getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            purchaseCartRecycler.scrollTo(0,purchaseCartRecycler.getHeight());
        },100);
    }

    /**
     * 处理编辑状态
     */
    private void doEditStatus() {
        for (int i = 0; i < cartData.getProducts().size(); i++) {
            for (int j = 0; j < cartData.getProducts().get(i).getSku_info().size(); j++) {
                cartData.getProducts().get(i).getSku_info().get(j).setIsEdit(isEdit);
            }
        }
        cartAdapter.notifyDataSetChanged();
    }

    /**
     * 给主商品id赋值
     */
    private void doMainProductId() {
        for (int i = 0; i < cartData.getProducts().size(); i++) {
            cartData.getProducts().get(i).setProduct_main_id(cartData.getProducts().get(i).getSku_info().get(0).getProduct_main_id());
        }
    }

    /**
     * 主商品勾选处理
     */
    private void doMainGoodsCheck(String productId, boolean isSelected) {
        for (int i = 0; i < cartData.getProducts().size(); i++) {
            if (cartData.getProducts().get(i).getProduct_main_id().equals(productId)) {
                cartData.getProducts().get(i).setIsSelected(isSelected);
            }
            for (int j = 0; j < cartData.getProducts().get(i).getSku_info().size(); j++) {
                if (cartData.getProducts().get(i).getSku_info().get(j).getProduct_main_id().equals(productId)) {
                    cartData.getProducts().get(i).getSku_info().get(j).setIsSelected(isSelected);
                }
            }
        }
        cartAdapter.notifyDataSetChanged();
        doAllGoodsCheck();
    }

    /**
     * sku商品勾选处理
     */
    private void doSkuGoodsCheck(String productId, String carId, boolean isSelected) {
        for (int i = 0; i < cartData.getProducts().size(); i++) {
            for (int j = 0; j < cartData.getProducts().get(i).getSku_info().size(); j++) {
                if (cartData.getProducts().get(i).getSku_info().get(j).getCart_id().equals(carId)) {
                    cartData.getProducts().get(i).getSku_info().get(j).setIsSelected(isSelected);
                }
            }
        }
        for (int i = 0; i < cartData.getProducts().size(); i++) {
            for (int j = 0; j < cartData.getProducts().get(i).getSku_info().size(); j++) {
                if (cartData.getProducts().get(i).getSku_info().get(j).getProduct_main_id().equals(productId)) {
                    if (!cartData.getProducts().get(i).getSku_info().get(j).getIsSelected()) {
                        cartData.getProducts().get(i).setIsSelected(false);
                        break;
                    } else {
                        cartData.getProducts().get(i).setIsSelected(true);
                    }
                }
            }
        }
        cartAdapter.notifyDataSetChanged();
        doAllGoodsCheck();
    }

    /**
     * 处理是否全选
     */
    private void doAllGoodsCheck() {
        boolean isAllSelect = true;
        for (int i = 0; i < cartData.getProducts().size(); i++) {
            for (int j = 0; j < cartData.getProducts().get(i).getSku_info().size(); j++) {
                if (!cartData.getProducts().get(i).getSku_info().get(j).getIsSelected()) {
                    isAllSelect = false;
                    break;
                }
            }
        }
        isAllSelected = isAllSelect;
        purchaseCartSelectedIcon.setImageResource(isAllSelected ?
                R.mipmap.dealer_radio_select : R.mipmap.dealer_radio_default);
        goodsSelectedClick();
    }

    /**
     * 已勾选商品请求处理
     */
    private void goodsSelectedClick() {
        showProgress();
        selectedList.clear();
        for (int i = 0; i < cartData.getProducts().size(); i++) {
            for (int j = 0; j < cartData.getProducts().get(i).getSku_info().size(); j++) {
                if (cartData.getProducts().get(i).getSku_info().get(j).getIsSelected()) {
                    selectedList.add(cartData.getProducts().get(i).getSku_info().get(j).getCart_id());
                }
            }
        }
        refreshData();
    }

    /**
     * 全选商品请求处理
     */
    private void allSelectedClick() {
        showProgress();
        selectedList.clear();
        if (!isAllSelected) {
            for (int i = 0; i < cartData.getProducts().size(); i++) {
                for (int j = 0; j < cartData.getProducts().get(i).getSku_info().size(); j++) {
                    selectedList.add(cartData.getProducts().get(i).getSku_info().get(j).getCart_id());
                }
            }
        }
        isAllSelected = !isAllSelected;
        for (int i = 0; i < cartData.getProducts().size(); i++) {
            cartData.getProducts().get(i).setIsSelected(isAllSelected);
            for (int j = 0; j < cartData.getProducts().get(i).getSku_info().size(); j++) {
                cartData.getProducts().get(i).getSku_info().get(j).setIsSelected(isAllSelected);
            }
        }
        purchaseCartSelectedIcon.setImageResource(isAllSelected ?
                R.mipmap.dealer_radio_select : R.mipmap.dealer_radio_default);
        refreshData();
    }

    /**
     * 请求后处理商品选中状态
     */
    private void doGoodsSelected() {
        for (int i = 0; i < cartData.getProducts().size(); i++) {
            for (int j = 0; j < cartData.getProducts().get(i).getSku_info().size(); j++) {
                //处理sku商品选中
                if (selectedList.contains(cartData.getProducts().get(i).getSku_info().get(j).getCart_id())) {
                    cartData.getProducts().get(i).getSku_info().get(j).setIsSelected(true);
                }
            }
        }

        for (int i = 0; i < cartData.getProducts().size(); i++) {
            for (int j = 0; j < cartData.getProducts().get(i).getSku_info().size(); j++) {
                //处理主商品选中
                if (cartData.getProducts().get(i).getProduct_main_id().equals(cartData.getProducts().get(i).getSku_info().get(j).getProduct_main_id())) {
                    if (!cartData.getProducts().get(i).getSku_info().get(j).getIsSelected()) {
                        cartData.getProducts().get(i).setIsSelected(false);
                        break;
                    } else {
                        cartData.getProducts().get(i).setIsSelected(true);
                    }
                }
            }
        }

        //处理编辑状态
        doEditStatus();
        //处理全选
        boolean isAllSelect = true;
        for (int i = 0; i < cartData.getProducts().size(); i++) {
            for (int j = 0; j < cartData.getProducts().get(i).getSku_info().size(); j++) {
                if (!cartData.getProducts().get(i).getSku_info().get(j).getIsSelected()) {
                    isAllSelect = false;
                    break;
                }
            }
        }
        isAllSelected = isAllSelect;
        purchaseCartSelectedIcon.setImageResource(isAllSelected ?
                R.mipmap.dealer_radio_select : R.mipmap.dealer_radio_default);
    }

    private void refreshData() {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < selectedList.size(); i++) {
            buffer.append(selectedList.get(i));
            if (i != selectedList.size() - 1) {
                buffer.append(",");
            }
        }
        Log.e("======", "refreshData: " + selectedList.size());
        cart_ids = buffer.toString();
        mPresenter.getData(cart_ids);
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshData();
    }

    @OnClick({R.id.purchase_cart_notice_icon, R.id.purchase_cart_confirm, R.id.purchase_cart_selected_layout, R.id.tv_purchase_cart_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.purchase_cart_notice_icon:
                startActivitry(BridgeActivity.class, new String[][]{{"url", cartData.getTop_tips_url()}});
                break;
            case R.id.purchase_cart_confirm:
                if (Long.parseLong(cartData.getCart_num()) < 1) {
                    ToastUtil.showToast("请至少购买一件哦");
                    return;
                }
                goodsDialog = new SelectGoodsDialog(getActivity(), custodyType -> {
                    showProgress();
                    mPresenter.confirmOrder(getProductsStr(), "1", custodyType);
                });
                goodsDialog.show();
                break;
            case R.id.purchase_cart_selected_layout:
                allSelectedClick();
                break;
            case R.id.tv_purchase_cart_delete:
                if (Long.parseLong(cartData.getCart_num()) < 1) {
                    ToastUtil.showToast("请选择要删除的商品");
                    return;
                }
                ConfirmDialog dialog = new ConfirmDialog(NewPurchaseShopCartActivity.this, "", null, "确定删除此商品吗", "取消", "确定", "#FF6809");
                dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                    @Override
                    public void cancel() {
                        dialog.dismiss();
                    }

                    @Override
                    public void confirm() {
                        showProgress();
                        mPresenter.deleteData(cart_ids);
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
        }
    }

    private String getProductsStr() {
        JSONObject productsStr = new JSONObject();
        try {
            if (selectedList.size() > 0) {
                for (int i = 0; i < cartData.getProducts().size(); i++) {
                    for (int j = 0; j < cartData.getProducts().get(i).getSku_info().size(); j++) {
                        if (selectedList.contains(cartData.getProducts().get(i).getSku_info().get(j).getCart_id())) {
                            productsStr.put(cartData.getProducts().get(i).getSku_info().get(j).getProduct_id(),
                                    cartData.getProducts().get(i).getSku_info().get(j).getBuy_qty());
                        }
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return productsStr.toString();
    }

    @Override
    public void showData(PurchaseCartData cartData) {
        dismissProgress();
        this.cartData = cartData;

        doMainProductId();
        if (TextUtils.isEmpty(cartData.getTop_tips_text())) {
            purchaseCartNoticeLayout.setVisibility(View.GONE);
        } else {
            purchaseCartNoticeLayout.setVisibility(View.VISIBLE);
            purchaseCartNoticeText.setText(cartData.getTop_tips_text());
        }
        setPriceStyle("¥ " + cartData.getConfirm_price());
        purchaseCartConfirm.setText(String.format("选好了(%s)", cartData.getCart_num()));
        purchaseCartNum.setText(String.format("共计%s件", cartData.getConfirm_num()));
        purchaseCartBottomLayout.setVisibility(cartData.getProducts().size() > 0 ? View.VISIBLE : View.GONE);
        emptyView.setVisibility(cartData.getProducts().size() > 0 ? View.GONE : View.VISIBLE);

        doGoodsSelected();
        cartAdapter.setNewData(cartData.getProducts());
    }

    @Override
    public void showFailure(String msg) {
        dismissProgress();
        ToastUtil.showToast(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (rxBus != null) rxBus.unregister(Config.PURCHASE_SUBMIT_ORDER);
    }

    /**
     * type:0 修改数目、type:1 删除商品回调
     */
    @Override
    public void operationalResult(boolean isSuccess, int type, String msg) {
        if (isSuccess) {
            if (type == 1) {
                selectedList.clear();
            }
            refreshData();
        } else {
            dismissProgress();
            ToastUtil.showToast(msg);
        }
    }

    @Override
    public void confirmOrderSuccess(ConfirmOrderData data,String isCustody) {
        dismissProgress();
        ARouter.getInstance().build(AroutePath.ORDER_SUBMIT_ACTIVITY).withString("buy_type", "1").
                withString("buy_product", getProductsStr()).withString("saleType", "4")
                .withString("is_custody", isCustody)
                .withSerializable("confirm_order_data", data).navigation();
    }

    private void showProgress() {
        if (progressDialog == null) {
            progressDialog = new ProgressLoginDialog(this);
        }
        progressDialog.show();
        progressDialog.setDesc("");
    }

    private void dismissProgress() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    private void setPriceStyle(String price) {
        SpannableString spannableString = new SpannableString(price);
        spannableString.setSpan(new RelativeSizeSpan(0.63f), 0, 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 2, price.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        if (price.contains(".")) {
            spannableString.setSpan(new RelativeSizeSpan(0.68f), price.indexOf("."), price.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        }
        purchaseCartPrice.setText(spannableString);
    }
}
